package org.qiyu.live.im.core.server.service.impl;

import com.alibaba.fastjson.JSON;
import jakarta.annotation.Resource;
import org.apache.rocketmq.client.producer.MQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.idea.qiyu.live.framework.redis.starter.key.ImCoresServerProviderCacheKeyBuilder;
import org.qiyu.live.common.interfaces.topic.ImCoreServerProviderTopicNames;
import org.qiyu.live.im.core.server.service.IMsgAckCheckService;
import org.qiyu.live.im.dto.ImMsgBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Description: TODO
 * @Author zhangguangyan
 * @Date 2023/10/03/ 00:47:02
 */
@Service
public class IMsgAckCheckServiceImpl implements IMsgAckCheckService {
private static final Logger logger = LoggerFactory.getLogger(IMsgAckCheckServiceImpl.class);
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private ImCoresServerProviderCacheKeyBuilder cacheKeyBuilder;
    @Resource
    private MQProducer mqProducer;
    @Override
    public void doMsgAck(ImMsgBody imMsgBody) {
        redisTemplate.opsForHash().delete(cacheKeyBuilder.buildImAckMapKey(imMsgBody.getUserId(),imMsgBody.getAppId()),imMsgBody.getMsgId());
    }

    @Override
    public void recordMsgAck(ImMsgBody imMsgBody,int times) {
        redisTemplate.opsForHash().put(cacheKeyBuilder.buildImAckMapKey(imMsgBody.getUserId(),imMsgBody.getAppId()),imMsgBody.getMsgId(),times);
    }

    @Override
    public void sendDelayMsg(ImMsgBody imMsgBody) {
        //用mq发送消息
        String json = JSON.toJSONString(imMsgBody);
        Message message = new Message();
        message.setBody(json.getBytes());
        message.setTopic(ImCoreServerProviderTopicNames.QIYU_LIVE_IM_ACK_MSG_TOPIC);
        //设置延迟时间 等级1为1s 2为5s
        message.setDelayTimeLevel(2);
        try {
            SendResult sendResult = mqProducer.send(message);
            logger.info("[IMsgAckCheckServiceImpl] msg is {},sendResult is {}",json,sendResult);
        } catch (Exception e) {
            logger.error("[IMsgAckCheckServiceImpl] sendDelayMsg error",e);
        }
    }

    @Override
    public int getMsgAckTimes(String msgId, long userId, int appId) {
        Object value = redisTemplate.opsForHash().get(cacheKeyBuilder.buildImAckMapKey(userId, appId), msgId);
        if (value ==null){
            return -1;
        }
        return (int) value;
    }
}
